package se.webbzon.oschi01.tools.mapper;

import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileInputStream;
import java.util.Map;

import javax.swing.AbstractAction;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import se.webbzon.oschi01.gui.LoadingFrame;
import se.webbzon.oschi01.item.ItemEntry;
import se.webbzon.oschi01.item.ItemSet;
import se.webbzon.oschi01.item.ItemSetReader;

public class MapperToolAction extends AbstractAction {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 323415895057780123L;

	public MapperToolAction() {
		this.putValue(NAME, "Mapper tool");
	}

	@Override public void actionPerformed(ActionEvent arg0) {
		JFileChooser chooser = new JFileChooser();
		
		// Get old file
		chooser.setDialogTitle("Select old entry file...");
		int val = chooser.showOpenDialog(null);
		if (val != JFileChooser.APPROVE_OPTION)
			return;
		
		// Parse old entry file
		File file = chooser.getSelectedFile();
		ItemSet oldSet = readItemSet(file);
		if (oldSet == null)
			return;
		
		// Get new file
		chooser.setDialogTitle("Select new entry file...");
		val = chooser.showOpenDialog(null);
		if (val != JFileChooser.APPROVE_OPTION)
			return;
		
		// Parse new entry file
		file = chooser.getSelectedFile();
		ItemSet newSet = readItemSet(file);
		if (newSet == null)
			return;
		
		// Match entries
		Map<ItemEntry,ItemEntry> entryMap = oldSet.mapTo(newSet);
		/*Collection<ItemEntry> unmappedEntries = new ArrayList<ItemEntry>();
		for (ItemEntry e : oldSet) {
			if (!entryMap.containsKey(e))
				unmappedEntries.add(e);
		}*/
		
		MapperModel model = new MapperModel(oldSet, newSet);
		model.mapItems(entryMap);
		new MapperFrame(model);
	}
	
	private static final ItemSet readItemSet(File file) {
		LoadingFrame frame = new LoadingFrame("Loading entries...","Please wait while item entries are loaded...");
		frame.setValue(50);
		frame.setLocationRelativeTo(null);
		frame.repaint();
		ItemSet set = null;
		try (FileInputStream fis = new FileInputStream(file)) {
			frame.setVisible(true);
			ItemSetReader reader = new ItemSetReader();
			int entries = reader.read(fis);
			fis.close();
			frame.setValue(100);
			JOptionPane.showMessageDialog(null,"Successfully read " + entries + " item entries.","Complete",JOptionPane.INFORMATION_MESSAGE);
			set = reader.getItemSet();
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null,e.getMessage(),"Error",JOptionPane.ERROR_MESSAGE); 
		}
		frame.setVisible(false);
		frame.dispose();
		return set;
	}

}
